package logic

import (
	"context"
	"errors"
	"fresh-box-mgr/freshrpc/freshrpc"
	"fresh-box-mgr/freshrpc/internal/svc"
	"fresh-box-mgr/model"
	"github.com/zeromicro/go-zero/core/logx"
)

type AddFreshLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddFreshLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddFreshLogic {
	return &AddFreshLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddFreshLogic) AddFresh(in *freshrpc.AddFreshRequest) (*freshrpc.AddFreshResponse, error) {
	// todo: add your logic here and delete this line
	var FindFresh model.Fresh
	begin := model.DB.Begin()
	err := FindFresh.FindFreshByFreshName(begin, in.FreshName)
	if err == nil {
		return nil, errors.New("该商品已存在")
	}
	//if FindFresh.ID != 0 {
	//	return nil, errors.New("该商品已存在")
	//}
	var class model.Class

	if err := class.FindFreshByName(begin, in.ClassName); err != nil {
		class = model.Class{
			//Model:     gorm.Model{},
			ClassName: in.ClassName,
		}

		if err = class.CreatedClass(begin); err != nil {
			return nil, errors.New("该商品添加失败")
		}
	}
	fresh := &model.Fresh{
		//Model:       gorm.Model{},
		FreshName:   in.FreshName,
		FreshImages: in.FreshImages,
		FreshNum:    int(in.FreshNum),
		ClassId:     int(class.ID),
	}

	if err = fresh.CreateFresh(begin); err != nil {
		return nil, errors.New("添加商品失败")
	}
	begin.Commit()
	return &freshrpc.AddFreshResponse{
		FreshId: int64(fresh.ID),
	}, nil
}
